package com.qqt.csr.common.config;

import com.qqt.csr.common.exception.BaseException;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.vo.resp.BaseResponse;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理请求参数格式错误 @RequestBody 上使用 @Valid 实体上使用 @NotNull 等，验证失败后抛出的异常是 MethodArgumentNotValidException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return new BaseResponse().setCode(StatusCode.Common.ILLEGAL_PARAM_ERROR.getCode()).setMessage(message);
    }

    /**
     * 处理 Get 请求中 使用 @Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    public BaseResponse bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return new BaseResponse().setCode(StatusCode.Common.ILLEGAL_PARAM_ERROR.getCode()).setMessage(message);
    }

    /**
     * 处理请求参数格式错误 @RequestParam 上 @Validate 失败后抛出的异常是 ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return new BaseResponse().setCode(StatusCode.Common.ILLEGAL_PARAM_ERROR.getCode()).setMessage(message);
    }

    /**
     * 参数格式异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseResponse httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException e) {
        return new BaseResponse().setCode(StatusCode.Common.ILLEGAL_PARAM_ERROR.getCode()).setMessage("参数格式异常");
    }

    /**
     * 业务异常处理
     */
    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHandler(BaseException e) {
        return new BaseResponse().setCode(e.getCode()).setMessage(e.getMessage());
    }

    /**
     * Throwable 处理
     */
    @ExceptionHandler(Throwable.class)
    public BaseResponse exceptionHandler(Throwable e) {
        log.error("系统错误", e);
        return new BaseResponse().setCode(StatusCode.Common.INTERNAL_SERVER_ERROR.getCode()).setMessage(StatusCode.Common.INTERNAL_SERVER_ERROR.getMessage());
    }
}
